<?php
namespace interface\v1;
/*
*费用申请接口类
*/

use verify;

class feeApplyAppClass extends index
{
    private const page = 'feeApply';
    private const table = 'cost';
    private const title = '费用申请';
    public array $stateOption = ['草稿','审核中','已通过'];
    /*查询条件*/
    public function search()
    {
        //状态
        $data['result']['stateOption'] = $this->stateOption;
        $data['result']['timeOption'] = $this->timeOption;
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /*列表页*/
    public function list()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            'classify'=>1,
            "state" => $this->post('state'),//审批状态
            "coid"=>self::$coid
        );
        //初始化
        $and ='';
        if ($this->post('keyword')) {
            $and .= " and (reason like '%".$this->post('keyword')."%' or orderNo like '%".$this->post('keyword')."%')";
        }
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .=$this->miniTimeComparison($commitTime);
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'orderNo'=>$array['orderNo'],
                "money" => $array['money'],
                "reason" => $array['reason'],//事由
                "state" => $array['state'],//状态
                'time'=>date('m/d',strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 编辑页面
     */
    public function editPage(){
        $id = $this->post('id');
        $info = query(self::table,"id = '$id'");
        $this->code=1;
        $data=[];
        if ($id && empty($info['id'])){
            $this->code = 0;
            $this->resp['warn'] = '未找到此'.self::title;
        }elseif(!empty($info['id'])){
            $data['result'] = [
                'id'=>$id,
                'money'=>$info['money'],
                'bankNum'=>$info['bankNum'],
                'reason'=>$info['reason'],
                'text'=>$info['text'],
            ];
        }
        $this->resp['data'] = $data;
    }

    /**
     * 编辑
     */
    public function commitEdit(){
        $id = $this->post('id') ?: self::getId();
        $field = [
            'reason' => $this->post('reason'),
            'money' => $this->post('money'),
            'bankNum' => $this->post('bankNum'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'reason' => '事由',
            'money' => '金额',
            'bankNum' => '收款账号',
        ];
        $rules = [
            'reason' => 'required',
            'money' => 'required|numeric',
            'bankNum' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "你没有编辑" . self::title . "的权限";
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = self::generateCode(self::page,[
                    'prefix' => 'FYSQ'.date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department'," id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => $id,
                    'classify'=>1,
                    'coid'=>self::$coid,
                    'deptName'=>$department['name'],
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $this->resp['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $this->resp['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                $this->resp['data']['id'] = $id;
                //返回
                $this->code=1;
            }
        }
        resp:
    }

    /*详情页*/
    public function detail()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '" . $id . "'");
        if (empty($id)) {
            $this->resp['warn'] = "ID为空";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } else {
            //申请人
            $staff = query("staff", "stid = '$info[stid]'");
            $audit = query('audit',"targetId = '$info[id]'");
            $record = auditAppClass::auditRecord(self::table,$id);
            $auditRecord = [];
            $active = 0;
            if ($record !==false){
                $auditRecord = $record['record'];
                $active = $record['active'];
            }
            $data['result'] = [
                'id'=>$id,
                'staffName'=>$staff['name'],
                'flowName'=>'费用申请',
                'ico'=>self::fillSrc($this->control['ico'],$this->control['updateTime']),
                'orderNo'=>$info['orderNo'],
                'text'=>$info['text'],
                'money'=>$info['money'],
                'bankNum'=>$info['bankNum'],
                'reason'=>$info['reason'],
                'commitTime'=>$audit['commitTime'],
                'deptName'=>$info['deptName'],
                'state'=>$info['state'],
                'stid'=>$info['stid'],
                'role'=>auditAppClass::role(self::table,$id),
                'auditRecord'=>$auditRecord,
                'active'=>$active,
            ];
            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的".self::title;
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此".self::title."不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //删除audit表记录
                delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                //删除待办事项
                delete(array("table" => "backlog","where" => " typeId = '$id' "));
                //删除审批记录
                delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                //删除消息提醒
                delete(array("table" => "message","where" => " typeid = '$id' "));
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }
}
